import {
    initView,
    createRecord,
    showCostDialog,
    showLoadingDialog,
    hideLoadingDialog
} from '../views/tradeDetailView.js';

import {} from '../base/observer.js';
var cw = require("../components/winLocation.js");

import {
    Logout
} from '../components/logout.js';
var logoutObject;


var token, loginName, openid, loginType, orderId, goodsAmount;
var recordScroll;
var pageNum = 1,
    pageSize = 20;
var $wrapper;
var downUp = 1; // 1 表示下一页 0 上一页
var refundsType = "01"; // 01 正常退货 02 非免息退货
var measurementAmount = 0; // 非免息退金额
var cancelInterest = 0; // 罚息
var serial_no; // 撤销交易串号
$(document).on("pageinit", "#tradeDetail_page", controllerInit);

// 交易查询控制器初始化
function controllerInit() {
    cw.checkBrowser();
    initValue();
    initView();
    subscribeRecordData();
    bindEvent();
}


// 取交易记录数据
function subscribeRecordData() {
    showLoadingDialog();
    var srParameters = {
        "token": token,
        "loginName": loginName,
        "bizLicNo": loginName,
        "openid": openid,
        "loginType": loginType,
        "pageNum": pageNum,
        "pageSize": pageSize
    };

    $.post(TransactionSevlet_URL, srParameters, TRback);


}

// 交易记录回调函数
function TRback(trData) {
    hideLoadingDialog();
    if (trData.login_response) {
        haslogin(trData);
        return;
    }
    if (trData.tltdtrans_response && trData.tltdtrans_response.trans_info_arrays && trData.tltdtrans_response.trans_info_arrays.trans_info) {
        var $cells = $("#record_cells");
        var transInfos = trData.tltdtrans_response.trans_info_arrays.trans_info
        sessionStorage.setItem("tradeDetail_page", pageNum);
        if (!transInfos || transInfos.length < 20) {
            $wrapper.find('#pullup-label').html("没有更多记录了");
        } else if (transInfos.length == 20) {
            $wrapper.find('#pullup-label').html("上拉加载更多...");
        }
        if (recordScroll) {
            recordScroll.scrollTo(0, 0, 0);
        }
        if (transInfos.length == 0) {
            $.alert("没有交易记录");
        } else {
            if (transInfos.length == undefined) { // 只有一条记录时返回的是对象不是数组处理
                var oneTransInfos = [];
                oneTransInfos.push(transInfos);
                transInfos = oneTransInfos;
            }
            createRecord(transInfos, $cells);
            $("#billText>span").text("(第" + pageNum + "页)");
            if (recordScroll) {
                recordScroll.refresh();
            }

        }


    } else if (trData.tltdtrans_response && trData.tltdtrans_response.resp_msg) {
        noMorePage();
        $.alert(trData.tltdtrans_response.resp_msg);
    } else {
        noMorePage();
        $.alert("查询交易记录失败");
    }


}

function noMorePage() {
    if (pageNum != 1) {
        pageNum--
    }
    $wrapper.find('#pullup-label').html("没有更多记录了");
}

// 退货请求
function returnGoods() {
  showLoadingDialog();
    var rgParameters = {
        "token": token,
        "loginName": loginName,
        "bizLicNo": loginName,
        "openid": openid,
        "loginType": loginType,
        "orderId": orderId,
        "goodsAmount": goodsAmount,
        "refundsType": refundsType,
        "measurementAmount": measurementAmount,
        "cancelInterest": cancelInterest
    };
    $.post(MerRefunds_URL, rgParameters, rgback);
}

//  退货回调函数
function rgback(rgdata) {
    hideLoadingDialog();
    if (rgdata.login_response) {
        haslogin(rgdata);
        return;
    }
    console.dir(rgdata);
    if (rgdata.lft_orderinfo_response && rgdata.lft_orderinfo_response.resp_code == "0000") {
        $.alert("退货申请成功");
    }else if (rgdata.lft_orderinfo_response && rgdata.lft_orderinfo_response.resp_code == "8888") {
        $.alert("退货成功");
    } else {
        $.alert("退货失败");
    }
    subscribeRecordData();
}

// 调工作时间接口
function workingHours (workingFuc,noworkingFuc) { // workingFuc 工作时间调用函数 ， noworkingFuc 非工作时间调用函数
    $.post(LFQCreateOrderServlet,{"servlet_type": "query_openday"},function  (wdata) {
        console.dir(wdata);
        var nowHours = (new Date()).getHours();
        if(wdata.openday_response.isOpenday == "1" && nowHours >7 && nowHours < 16){
            returnConst();
        }else{
            $.alert("免息期外退货申请后需要在当日打款，请与贵司财会同事确认后在工作日8点至16点间发起申请");
        }
    });
}

//  掉免息期外费用接口
function returnConst() {
    showLoadingDialog();
    var rgParameters = {
        "token": token,
        "bizLicNo": loginName,
        "orderId": orderId
    };
    $.post(MerDopeRefunds_URL, rgParameters, function  (constdata) {
        hideLoadingDialog();
        if(constdata.lfq_search_order_response && constdata.lfq_search_order_response.resp_code == "0000"){
            if(constdata.lfq_search_order_response.remainAmount != 0){
                var cAmount = (constdata.lfq_search_order_response.costAmount).toFixed(2);
                $("#return_cost").text(cAmount);
                measurementAmount = (constdata.lfq_search_order_response.cancelAmount/100).toFixed(2);;
                cancelInterest = constdata.lfq_search_order_response.cancelInterest/100;
                showCostDialog();
            }else{
               $.alert("该分期订单已全额还款，无法申请退货");
            }

        }else{
            $.alert("退回结算款项及利息取值失败");
        }
    });
}

// 点击订单详情列表到订单详情页
function linkOrderDetail(e) {
    var trans_seq;

    if ($(e.target).attr("data-goods_Amount")) {
        if ($(e.target).hasClass("weui-btn_plain-disabled")) {
            return;
        } else {
            goodsAmount = $(e.target).attr("data-goods_Amount");
            orderId = $(e.target).attr("data-order_id");
            var iscost = $(e.target).attr("data-cost");
            if(iscost == "1"){ // 调结算款接口 成功调showCostDialog 否则 弹个提示 2017.08.22
//                returnConst();
              workingHours();
            }else if(iscost == "2"){
              serial_no = $(e.target).attr("data-serial_no");
              $.confirm("是否撤销这笔交易", function(serial_no) {
                //点击确认后的回调函数
                rescission()
              }, function() {
              //点击取消后的回调函数
              });
            }else{
              $.confirm("是否退回该笔订单", function(serial_no) {
                //点击确认后的回调函数
                refundsType = "01";
                measurementAmount = 0;
                returnGoods();
              }, function() {
              //点击取消后的回调函数
              });
            }

        }
    } else if ($(e.target).attr("data-trans_seq")) {
        trans_seq = $(e.target).attr("data-trans_seq");
    } else {
        var theParnet = $(e.target).parents("[data-trans_seq]");
        if (theParnet[0]) {
            trans_seq = theParnet.attr("data-trans_seq");
        }
    }
    if (trans_seq) {
        location.href = "./orderDetail.html?trans_seq=" + trans_seq;
    }
}

// 判断是否有效登入
function haslogin(msg) {
    if (msg.login_response) {
        $.alert("该账户已在别的地方登录,请重新登入");
        setTimeout(function() {
            location.href = LoginInit_URL;
        }, 3000);
    }
}

// 绑定事件
function bindEvent() {
    var endY, startY;
    $("#record_cells").on("touchstart", function() {
        var touch = event.targetTouches[0];
        startY = touch.pageY;
        endY = touch.pageY;
    });
    $("#record_cells").on("touchmove", function() {
        var touch = event.targetTouches[0];
        endY = touch.pageY;
    });
    $("#record_cells").on("touchend", function(event) {
        setTimeout(function() {
            if ((startY - endY) < 5 && (startY - endY) > -5) {
                linkOrderDetail(event);
            }
        }, 50);

    });
    $("#cost-yes").on("touchend",function  () {
        $("#prompt-return_cost").fadeOut(200);
        refundsType = "02";
        returnGoods();
    });
    initIscroll();
}


/*-----------------------------------
滚动模块 */

function initIscroll() {
    var pullText = {
        "pulldownRefresh": "下拉刷新...",
        "pullupLoadingMore": '上拉加载更多...',
        "releaseToRefresh": '松手开始刷新...',
        "releaseToLoading": '松手开始加载...',
        "loading": '加载中...'
    };
    setTimeout(function() {
        recordScroll = new IScroll('#iScroll-box');

        //滚动结束之后触发的事件
        recordScroll.on('scrollEnd', function() {
            console.log("dfksjd");
            var $pulldown = $wrapper.find('#pulldown'),
                $pullup = $wrapper.find('#pullup');

            if ($pulldown.length > 0 && this.y >= 0) {
                $pulldown.removeClass().addClass('loading');
                $pulldown.find('#pulldown-label').html(pullText.releaseToRefresh);
                if (typeof pullDownAction === 'function') {
                    pullDownAction.call(recordScroll);
                }
            } else if ($pulldown.length > 0 && this.y < -5 && this.y > this.maxScrollY + 5) {
           //     $pullup.find('#pullup-label').html(pullText.pullupLoadingMore);
            } else if ($pullup.length > 0 && this.y <= this.maxScrollY) {
                $pullup.removeClass().addClass('loading');
                $pullup.find('#pullup-label').html(pullText.loading);
                if (typeof pullUpAction === 'function' && $pullup.parent().length > 0) {
                    pullUpAction.call(recordScroll);
                }
            }
        });

    }, 800);
}
/**
 * 下拉刷新
 */
function pullDownAction() {
    console.log("pullDownAction");
    if (pageNum > 1) {
        pageNum--;
    } else {
        pageNum = 1;
    }

    downUp = 0;
    subscribeRecordData();

}

/*上拉加载更多*/
function pullUpAction() {
    pageNum++;
    downUp = 1;
    subscribeRecordData();
}

/* 滚动模块
-------------------------------------------*/
/* -------------------------------------------
 撤销交易 --*/
 // 撤销交易
function rescission() {
  showLoadingDialog();
    var rgParameters = {
        "token": token,
        "loginName": loginName,
        "bizLicNo": loginName,
        "openid": openid,
        "loginType": loginType,
        "orderId": orderId,
        "serial_no": serial_no
    };
    $.post(MerConsumeRevokeServlet_URL, rgParameters, rescissionsBack);
}

// 撤销交易回调函数
function rescissionsBack(rdata) {
  if(rdata.lft_orderinfo_response && rdata.lft_orderinfo_response.resp_code == "0000"){
    $.alert("撤销成功")
    subscribeRecordData()
  }else if(rdata.lft_orderinfo_response && rdata.lft_orderinfo_response.resp_msg){
    $.alert("撤销交易失败," + rdata.lft_orderinfo_response.resp_msg)
  }else{
    $.alert("撤销交易失败")
  }
  console.log("撤销交易回调函数")
  console.dir(rdata)
}

/*--------------------------------*/

// 初始化变量
function initValue() {
    getSessionStorage();
    logoutObject = new Logout();
    $wrapper = $('#iScroll-box');
}



// 取本地存储essionStorage
function getSessionStorage() {
    token = sessionStorage.getItem("tltd_token");
    loginName = sessionStorage.getItem("tltd_loginName");
    openid = sessionStorage.getItem("tltd_openid");
    loginType = sessionStorage.getItem("tltd_loginType");
    var pageNumSession = sessionStorage.getItem("tradeDetail_page");
    if (pageNumSession) {
        pageNum = pageNumSession;
    }
    console.log(token, loginName, openid, loginType);
}
